from ..models.user_model import Users
from sqlalchemy.orm import Session
from sqlalchemy import select, update
from fastapi import HTTPException


def get_users(db: Session):
    query = select(Users).order_by(Users.id.asc())
    result= db.execute(query).scalars().all()
    if not result:
        raise HTTPException(status_code=404, detail="No users found")
    return result

def get_user_by_name(db: Session, name):
    result=db.execute(select(Users).where(Users.username == name)).scalar()
    if not result:
        raise HTTPException(status_code=404, detail="No users found")
    return result

def create_user(db: Session, student_data):
    if db.execute(select(Users).where(Users.username == student_data.username)).scalars().first():
        raise HTTPException(status_code=400, detail=f"Student {student_data.username} already exists")
    new_student = Users(**student_data.model_dump())
    db.add(new_student)
    db.commit()
    db.refresh(new_student)
    return new_student
def create_user1(db: Session, new_student):
    if db.execute(select(Users).where(Users.username == new_student.username)).scalars().first():
        raise HTTPException(status_code=400, detail=f"Student {new_student.username} already exists")

    db.add(new_student)
    db.commit()
    db.refresh(new_student)
    return new_student

def update_user(db: Session, student_id, student_data):
    exist_student = db.execute(select(Users).where(Users.id == student_id)).scalar()
    if not exist_student:
        raise HTTPException(status_code=404, detail=f"Student {student_id} not found")
    for k, v in student_data.model_dump().items():
        setattr(exist_student, k, v)
    db.commit()
    return exist_student


def delete_user(db: Session, student_id):
    exist_student = db.get(Users, student_id)
    if not exist_student:
        raise HTTPException(status_code=404, detail="Student not found")
    db.delete(exist_student)
    db.commit()
    return exist_student

def get_user_by_id(db: Session, student_id):
    return db.get(Users, student_id)

def check_user_exists(db: Session, student_id):
    return db.get(Users, student_id) is not None

# if __name__ == "__main__":
#     from database.db import SessionLocal
#     db = SessionLocal()
#     user=get_user_by_id(db,11)
#     for folder in user.folders:
#         print(folder.as_dict())